import java.util.Random;

public class PercolationStats {

    private double mean;
    private double stddev;

    // perform T independent computational experiments on an N-by-N grid
    public PercolationStats(int N, int T) {
        if (N <= 0 || T <= 0) {
            throw new IllegalArgumentException();
        }
        double[] x = new double[T];
        Random r = new Random();
        for (int t = 0; t < T; t++) {
            Percolation p = new Percolation(N);
            int opened = 0;
            while (!p.percolates()) {
                final int k = r.nextInt(N*N);
                final int i = k / N + 1;
                final int j = k % N + 1;
                if (!p.isOpen(i, j)) {
                    p.open(i, j);
                    opened++;
                }
            }
            x[t] = ((double) opened)/N/N;
            this.mean += x[t];
        }
        this.mean /= T;
        for (int t = 0; t < T; t++) {
            this.stddev += (x[t] - mean) * (x[t] - mean);
        }
        this.stddev /= T-1;
        this.stddev = Math.sqrt(this.stddev);
    }

    // sample mean of percolation threshold
    public double mean() {
        return this.mean;
    }

    // sample standard deviation of percolation threshold
    public double stddev() {
        return this.stddev;
    }

    // test client, described below
    public static void main(String[] args) {
        int N =  Integer.parseInt(args[0]);
        int T =  Integer.parseInt(args[1]);
        PercolationStats ps = new PercolationStats(N, T);
        System.out.println("mean                    = " + ps.mean());
        System.out.println("stddev                  = " + ps.stddev());
        System.out.println("95% confidence interval = " + (ps.mean() - 1.96*ps.stddev()/Math.sqrt(T)) + ", " + (ps.mean() + 1.96*ps.stddev()/Math.sqrt(T)));
    }

}
